#include "module/edit_camera_parameters.h"
#include <QFile>
#include <QtXml>
#include <iostream>
#include <QDomDocument>
#include <QMessageBox>
#include <yaml-cpp/yaml.h>
#include <ros/package.h>

namespace camera_calibration {
EditCameraParamenters::EditCameraParamenters() {}

void EditCameraParamenters::EditStartupFile(
    const int _image_width, const int _image_height, const int _device_id ,int& _edit_status) {
  QString _device = "/dev/video" + QString::number(_device_id);

  QString tempFile = "/tmp/usb_cam_modified.launch";

  if (QFile::exists(tempFile)) {
      QFile::remove(tempFile);
  }

  QFile::copy("/opt/ros/noetic/share/usb_cam/launch/usb_cam-test.launch", tempFile);


  QFile file(tempFile);
  if (QFile::exists(tempFile))
  {
    file.setPermissions(QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::WriteUser);
    file.close();
  }else {
    _edit_status = 0;
    return;
  }

  if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {
    qWarning() << "无法打开文件:" << tempFile << "错误:" << file.errorString();
    _edit_status = 0;
    return;
  }

  QDomDocument doc;

  if (!doc.setContent(&file)) {
    QMessageBox::information(NULL, "提示", "操作的文件不是XML文件！");
    file.close();
    _edit_status = 0;
    return;
  }

  QDomElement root = doc.documentElement();
  QDomNodeList list = root.elementsByTagName("node");
  for (int i = 0; i < list.size(); ++i) {
    QDomElement node = list.at(i).toElement();
    if (node.attribute("name") == "usb_cam") {
      QDomNodeList paramList = node.elementsByTagName("param");
      for (int j = 0; j < paramList.size(); ++j) {
        QDomElement param = paramList.at(j).toElement();
        QString name = param.attribute("name");
        if (name == "video_device") {
          param.setAttribute("value", _device);
        } else if (name == "image_width") {
          param.setAttribute("value", QString::number(_image_width));
        } else if (name == "image_height") {
          param.setAttribute("value", QString::number(_image_height));
        }
      }
      break;
    }
  }

  file.resize(0);
  QTextStream stream(&file);
  doc.save(stream, 2);
  file.close();
  _edit_status = 1;
}

void EditCameraParamenters::ReadCameraDefaultParameters(
  int& _image_width, int& _image_height, int&_device_id) {

  std::string package_path = ros::package::getPath("camera_calibration_studio");

  std::string config_path = package_path + "/config/default_parameters.yaml";

  YAML::Node config = YAML::LoadFile(config_path);
  YAML::Node camera = config["camera"];
  _image_width = camera["image_width"].as<int>();
  _image_height = camera["image_height"].as<int>();
  _device_id = camera["device_id"].as<int>();
}

} //namespace camera_calibration
